<template>
  <div class="cremation_statistics overflowY" v-loading="loading">
    <div class="PageContent">
      <el-form
        :model="ruleForm"
        :inline="true"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <div class="PageItem margintop20">
          <el-row class="paddingleft2em">
            <el-form-item prop="reserveDate">
              <el-date-picker
                v-model="ruleForm.reserveDate"
                type="year"
                placeholder="选择年"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                v-if="btnRight.btnSearch"
                @click="submitForm('ruleForm')"
                >查询</el-button
              >
            </el-form-item>
          </el-row>
        </div>
      </el-form>
      <div class="PageItem">
        <div id="myBarCharts" ref="myBarCharts"></div>
      </div>
      <div class="PageItem">
        <div id="myPieCharts" ref="myPieCharts"></div>
      </div>
      <div class="PageItem">
        <div id="myLineCharts" ref="myLineCharts"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as API from '@/api/civilAffairsBureau/index'
export default {
  data() {
    return {
      loading: false, //加载
      myBarCharts: null, //柱状图
      myPieCharts: null, //饼图
      myLineCharts: null, //折线图
      allBarData: [], //返回柱状图表数据
      allPieData: [], //返回饼图数据
      allLineData: [], //返回折线数据
      startValue: 0, // 区域缩放的起点值
      endValue: 3, // 区域缩放的终点值
      timerId: null,
      colorArr:["#A35AE0","#00CA98","#f34e2b",'#FF9502','#33574B','#BB002B','#7EFF02','#D0FA58','#FE2EF7','#01DFD7','#AEB404','#FF8000'],// 定时器的标识
      ruleForm: {
        reserveDate: this.$dayjs(new Date()).format("YYYY"), //日期
      },
      pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
      },
       //按钮权限
        btnRight: {
          btnSearch: false,

        },
      rules:{
        reserveDate:[
          { required: true, message: '请输入年份', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    setTimeout(() => {
      this.getBarData();
      this.getPieLineData();
    }, 1000);
  },
  mounted() {
    //按钮权限
      this.btnRight = this.$route.meta.buttons;
      //遍历属性赋值将true与false字符串转换成布尔型的值
      for (var key of Object.keys(this.btnRight)) {
        this.btnRight[key] =
          this.btnRight[key] || this.btnRight[key] == "true" ? true : false;
      }
    //初始化柱状图表
    this.initMyBarCharts();
    //初始化饼图表
    this.initMyPieCharts();
    //初始化折线图
    this.initMyLineCharts();
    window.removeEventListener("resize", () => {
      this.myBarCharts.resize();
      this.myPieCharts.resize();
      this.myLineCharts.resize();
    });
  },
  methods: {
    //表单提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
          if (valid) {
            this.getBarData();
            this.getPieLineData()
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    //初始化柱状图表
    initMyBarCharts() {
      this.myBarCharts = this.$echarts.init(this.$refs.myBarCharts);
      const initOption = {
        grid: {
          left: 30,
          top: 80,
          right: 20,
          bottom: 20,
        },
        tooltip: {},
        legend: {
          show: true,
          icon: "circle",
          orient: "horizontal",
          top: "0.5%",
          right: "8%",
          itemWidth: 18.5,
          itemHeight: 6,
          itemGap: 30,
          textStyle: {
            // color: '#FFFFFF'
            color: "#C9C8CD",
          },
        },
        xAxis: {
          type: "category",
          data: [
            "一月",
            "二月",
            "三月",
            "四月",
            "五月",
            "六月",
            "七月",
            "八月",
            "九月",
            "十月",
            "十一月",
            "十二月",
          ],
        },
        yAxis: {},
        series: [],
      };
      this.myBarCharts.setOption(initOption);
      this.myBarCharts.on("mouseover", () => {
        clearInterval(this.timerId);
      });
      this.myBarCharts.on("mouseout", () => {
        this.startInterval();
      });
    },
    //获取柱状图数据
    async getBarData() {
      this.myBarCharts.showLoading();
      this.allBarData=[]
       let params={
          reserveDate:this.$dayjs(this.ruleForm.reserveDate).format("YYYY"),
        }
        const res = await API.findYearFuneralCremation(params)
        if(res.code==1){
          if(res.data.yearCemeteries!=null){
            res.data.yearCemeteries.forEach((item,index)=>{
              let obj={
                name: item.cremateName,
                type: "bar",
                barWidth: 20,
                itemStyle: {
                  normal: {
                    color: this.colorArr[index],
                    barBorderRadius: [10, 10, 0, 0],
                  },
                },
                data: item.cremateNumber
              }
              this.allBarData.push(obj)
            })
          }
        }else{
          this.$message.error('数据读取失败');
        }
        this.updateBarChart();
        this.startInterval();
    },
    //更新柱状图表
    updateBarChart() {
      const dataOption = {
        dataZoom: {
          show: false,
          startValue: this.startValue,
          endValue: this.endValue,
        },
        series: this.allBarData,
      };
      this.myBarCharts.setOption(dataOption);
      this.myBarCharts.hideLoading();
    },
    //启动定时器
    startInterval() {
      if (this.timerId) {
        clearInterval(this.timerId);
      }
      this.timerId = setInterval(() => {
        this.startValue++;
        this.endValue++;
        if (this.endValue > 11) {
          this.startValue = 0;
          this.endValue = 3;
        }
        this.updateBarChart();
      }, 2000);
    },
    //初始化饼图图表
    initMyPieCharts() {
      this.myPieCharts = this.$echarts.init(this.$refs.myPieCharts);
      const initOption = {
        color: this.colorArr,
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        toolbox: {
          show: true,
        },
        legend: {
          bottom: 0,
          textStyle: {
            color: "#8C8C8C",
          },
        },

        series: [],
      };
      this.myPieCharts.setOption(initOption);
    },
    //获取饼图数据
    async getPieLineData() {
     this.allPieData=[]
     this.allLineData=[]
       let params={
          reserveDate:this.$dayjs(this.ruleForm.reserveDate).format("YYYY"),
        }
        const res = await API.findYearCakeFuneralCremation(params)
        if(res.code==1){
          //处理饼图数据
          if(res.data.cremates!=null){
            res.data.cremates.forEach(item=>{
              let obj={
                name:item.funeralName,
                value:item.funeralNumber
              }
              this.allPieData.push(obj)
            })
          }
          //处理折线图数据
          if(res.data.yearCemeteries!=null){
            res.data.yearCemeteries.forEach((item,index)=>{
              let obj={
                name: item.cremateName,
                type: "line",
                smooth: true,
                //  symbol: "none", //去掉折线点
                stack: 100,
                itemStyle: {
                  normal: {
                    //颜色渐变函数 前四个参数分别表示四个位置依次为左、下、右、上
                    color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      {
                        offset: 0,
                        color: this.colorArr[index], // 0% 处的颜色
                      },
                      {
                        offset: 0.5,
                        color: this.colorArr[index], // 100% 处的颜色
                      },
                      {
                        offset: 1,
                        color: this.colorArr[index], // 100% 处的颜色
                      },
                    ]), //背景渐变色
                    lineStyle: {
                      // 系列级个性化折线样式
                      width: 2,
                      type: "solid",
                      color: this.colorArr[index],
                    },
                  },
                  emphasis: {
                    color: this.colorArr[index],
                    lineStyle: {
                      // 系列级个性化折线样式
                      width: 0.5,
                      type: "dotted",
                      color: this.colorArr[index], //折线的颜色
                    },
                  },
                }, //线条样式
                symbolSize: 9, //折线点的大小
                areaStyle: {
                  normal: {},
                },
                data: item.cremateNumber,
              }
              this.allLineData.push(obj)
            })
          }
        }else{
          this.$message.error('数据读取失败');
        }
      this.updatePieChart();
      this.updateLineChart()
    },
    //更新饼图
    updatePieChart() {
      const dataOption = {
        series: [
          {
            name: "火化量统计",
            type: "pie",
             label:{
                normal:{
                    formatter(v) {
                      let text = v.name
                      return text.length < 12
                          ? text

                          : `${text.slice(0,12)}\n${text.slice(12)}`
                    }
                }
            },
            radius: [0, 200],
            data: this.allPieData,
          },
        ],
      };
      this.myPieCharts.setOption(dataOption);
    },
    //初始化折线图图表
    initMyLineCharts() {
      this.myLineCharts = this.$echarts.init(this.$refs.myLineCharts);
      const initOption = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985",
            },
          },
        },
        color: [
          "#0080ff",
          "#4cd5ce",
          "rgba(11, 168, 44, 1)",
          "rgba(44, 110, 255,1)",
          "rgba(22, 242, 217, 1)",
          "rgba(254, 33, 30, 1)",
          "rgba(250, 105, 0, 1)",
        ],
        toolbox: {
          // feature: {
          //     saveAsImage: {}
          // }
        },
        grid: {
          left: "5%",
          right: "5%",
          top: "10%",
          bottom: "5%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            data: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月",],
            axisLabel: {
              show: true,
              textStyle: {
                color: "#333",
                fontSize: 16,
              },
              formatter: function (value) {
                //debugger
                var ret = ""; //拼接加\n返回的类目项
                var maxLength = 5; //每项显示文字个数
                var valLength = value.length; //X轴类目项的文字个数
                var rowN = Math.ceil(valLength / maxLength); //类目项需要换行的行数
                if (rowN > 1) {
                  //如果类目项的文字大于3,
                  for (var i = 0; i < rowN; i++) {
                    var temp = ""; //每次截取的字符串
                    var start = i * maxLength; //开始截取的位置
                    var end = start + maxLength; //结束截取的位置
                    //这里也可以加一个是否是最后一行的判断，但是不加也没有影响，那就不加吧
                    temp = value.substring(start, end) + "\n";
                    ret += temp; //凭借最终的字符串
                  }
                  return ret;
                } else {
                  return value;
                }
              },
            },
            axisLine: {
              lineStyle: {
                color: "#0a2b52",
                width: 0.5, //这里是为了突出显示加上的
              },
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "",
            axisLine: {
              onZero: false,
              lineStyle: {
                color: "#8398DE",
                width: 1, //这里是为了突出显示加上的
              },
            },
            axisLabel: {
              formatter: function (val) {
                return val + "";
              },
              show: true,
              textStyle: {
                color: "#333", //字体颜色
                fontSize: 18,
              },
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
              },
            },
          },
        ],
        series: [],
      };
      this.myLineCharts.setOption(initOption);
    },
    //更新折线图
    updateLineChart() {
      const dataOption = {
        series: this.allLineData
      };
      this.myLineCharts.setOption(dataOption);
    },
  },
  destroyed() {
    window.removeEventListener("resize", () => {
      this.myBarCharts.resize();
      this.myPieCharts.resize();
      this.myLineCharts.resize();
    });
    clearInterval(this.timerId);
  },
};
</script>

<style lang="scss" scoped>
.cremation_statistics {
  width: 100%;
  .PageItem {
    height: auto;
  }
  .PageContent /deep/ .el-input {
    width: 300px;
  }
  .PageContent /deep/ .el-select {
    width: 300px;
  }
  #myBarCharts {
    width: 100%;
    height: 500px;
  }
  #myPieCharts {
    width: 600px;
    height: 700px;
    margin: 0 auto;
  }
  #myLineCharts{
    width: 100%;
    height: 500px;;
  }
}
</style>
